package com.luguotao.lease.web.admin.controller.login;


import com.luguotao.lease.common.context.LoginUser;
import com.luguotao.lease.common.context.LoginUserContext;
import com.luguotao.lease.common.exception.LeaseException;
import com.luguotao.lease.common.result.Result;
import com.luguotao.lease.common.result.ResultCodeEnum;
import com.luguotao.lease.common.utils.JwtUtil;
import com.luguotao.lease.web.admin.service.LoginService;
import com.luguotao.lease.web.admin.service.SystemUserService;
import com.luguotao.lease.web.admin.vo.login.CaptchaVo;
import com.luguotao.lease.web.admin.vo.login.LoginVo;
import com.luguotao.lease.web.admin.vo.system.user.SystemUserInfoVo;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
@CrossOrigin
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    SystemUserService systemUserService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo captchaVo = loginService.getCaptcha();
        return Result.ok(captchaVo);
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        //前端把后端在验证码生成时候发出的token再带回来
        String token = loginService.login(loginVo);
        return Result.ok(token);
    }

//    @Operation(summary = "获取登陆用户个人信息")
//    @GetMapping("info")
//    public Result<SystemUserInfoVo> info(HttpServletRequest request) {
//        //验证token
//        String accssToken = request.getHeader("access_token");
//        if (accssToken==null){
//            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
//        }
//        Claims claims = JwtUtil.parseToken(accssToken);
//
//        Long userId = claims.get("userId", Long.class);
//        String userName = claims.get("userName", String.class);
//
//        //根据id查询用户信息
//        SystemUserInfoVo systemUserInfoVo = systemUserService.getUserService(userId);
//
//        return Result.ok(systemUserInfoVo);
//    }

    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info() {

        //为什么这里可以拿，因为在写拦截器的时候已经把负载放入了ThreadLocal中，并且是同一个线程
        LoginUser user = LoginUserContext.getUser();
        //根据用户的id查询用户的信息
        SystemUserInfoVo systemUserInfoVo=   systemUserService.getSysUserInfo(user.getUserId());

        return Result.ok(systemUserInfoVo);
    }
}